package com.yunzhou.action.fenbeitong;

import com.alibaba.fastjson.JSONObject;
import com.api.customization.fenbeitong.AccessTokenApi;
import com.yunzhou.utils.DBTools;
import com.yunzhou.utils.DateTools;
import com.yunzhou.utils.HttpClientUtils;
import com.yunzhou.utils.LogTool;
import org.apache.commons.codec.digest.DigestUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Date 2022-09-25
 * @Version 1.0
 * @Description TODO AD02 出差申请推送分贝通差旅信息，用车信息
 **/
public class TravelApplicationV2 extends BaseBean implements Action {
    private LogTool logTool = new LogTool("/log/fenbeitong/TravelApplication", false);

    private final HttpClientUtils client = new HttpClientUtils();
    private final DateTools dateTools = new DateTools();
    private final DBTools dbTools = new DBTools();

    @Override
    public String execute(RequestInfo requestInfo) {
        int requestid = requestInfo.getRequestManager().getRequestid();
        User user = requestInfo.getRequestManager().getUser();
        logTool.writeLog("开始推送出差申请单至分贝通,requestid="+requestid);

        Map<String,String> main = new HashMap<>();
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] properties = mainTableInfo.getProperty();
        for(Property property : properties){
            main.put(property.getName().toLowerCase(),property.getValue());
        }

        Map<String, Object> appInfo = new HashMap<>();
        try{
            appInfo = new AccessTokenApi().getAppInfo();
            if(!(boolean)appInfo.get("status")){
                requestInfo.getRequestManager().setMessageid(requestid+"");
                requestInfo.getRequestManager().setMessagecontent("getAppInfo error "+appInfo.get("code"));
                return FAILURE_AND_CONTINUE;
            }
            String app_url = (String) appInfo.get("app_url");
            String path_url = (String) appInfo.get("path_url");
            String app_id = (String) appInfo.get("app_id");
            String app_key = (String) appInfo.get("app_key");
            String sign_key = (String) appInfo.get("sign_key");
            String access_token = (String) appInfo.get("access_token");

            //构建参数
            Map<String, String> params = new HashMap<>();
            params.put("access_token", access_token);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            Map<String, Object> data = new HashMap<>();//请求数据
            Map<String, Object> data_apply = new HashMap<>();//申请单内容
            String apply_reason = main.get("qt");//备注
            data_apply.put("apply_reason",apply_reason);
            String third_id = ""+requestid;//第三方申请单id
            data_apply.put("third_id",third_id);
            int employee_id = requestInfo.getRequestManager().getCreater();//人员id
            data_apply.put("employee_id",main.get("shenqr"));
            String apply_reason_desc = main.get("qt");//备注
            data_apply.put("apply_reason_desc",apply_reason_desc);

            //费用归属对象集合
            List<Map<String,Object>> new_cost_attributions = new ArrayList<>();
            //费用归属 - 部门 start
            String feiygsbm = main.get("feiygsbm");
            if(!feiygsbm.equals("")){
                String[] alist = feiygsbm.split(",");
                for(int i=0;i<alist.length;i++){
                    Map<String,Object> cost_dep_main = new HashMap<>();
                    cost_dep_main.put("type","1");
                    cost_dep_main.put("third_archive_id",alist[i]);//费用归属部门
                    cost_dep_main.put("archive_name",dbTools.getDepNameById(alist[i]));//费用归属部门
                    List<Map<String,Object>> cost_dep_details = new ArrayList<>();
                    Map<String,Object> cost_dep_d1 = new HashMap<>();//费用归属 - 部门
                    cost_dep_d1.put("third_id",alist[i]);
                    cost_dep_d1.put("name",dbTools.getDepNameById(alist[i]));
                    cost_dep_details.add(cost_dep_d1);
                    cost_dep_main.put("details",cost_dep_details);
                    new_cost_attributions.add(cost_dep_main);
                }
            }
            //费用归属 - 部门 end

            //费用归属 - 项目 start
            String xiangmumc = main.get("xiangmumc");
            if(!xiangmumc.isEmpty()){
                Map<String,Object> cost_xm_main = new HashMap<>();
                cost_xm_main.put("type","2");
                cost_xm_main.put("third_archive_id",xiangmumc);//项目id
                cost_xm_main.put("archive_name",getXmmc(xiangmumc));//项目名称
                List<Map<String,Object>> cost_xm_details = new ArrayList<>();
                Map<String,Object> cost_xm_d1 = new HashMap<>();//项目明细
                cost_xm_d1.put("third_id",xiangmumc);
                cost_xm_d1.put("name",getXmmc(xiangmumc));
                cost_xm_details.add(cost_xm_d1);
                cost_xm_main.put("details",cost_xm_details);
                new_cost_attributions.add(cost_xm_main);
            }

            //费用归属 - 项目 end

            //费用归属 - 合同 start
            String htbh = main.get("htbh");
            if(!htbh.isEmpty()){
                Map<String,Object> cost_ht_main = new HashMap<>();
                cost_ht_main.put("type","2");
                cost_ht_main.put("third_archive_id",getHetlsh(htbh));//合同流水号
                cost_ht_main.put("archive_name",getHtmc(htbh));//合同名称
                List<Map<String,Object>> cost_ht_details = new ArrayList<>();
                Map<String,Object> cost_ht_d1 = new HashMap<>();//合同明细
                cost_ht_d1.put("third_id",getHetlsh(htbh));
                cost_ht_d1.put("name",getHtmc(htbh));
                cost_ht_details.add(cost_ht_d1);
                cost_ht_main.put("details",cost_ht_details);
                new_cost_attributions.add(cost_ht_main);
            }
            //费用归属 - 合同 end

            //添加费用归属内容
            data_apply.put("new_cost_attributions",new_cost_attributions);

            //获取明细表1
            int billid = requestInfo.getRequestManager().getBillid();
            String table = requestInfo.getRequestManager().getBillTableName();
            RecordSet rs = new RecordSet();
            rs.execute("select * from "+table+"_dt1 where mainid="+billid);
            List<String> citys = new ArrayList<>();//出差城市 包含出发地和目的地
            List<String> dates = new ArrayList<>();
            //同行人
            List<Map<String,Object>> guest_lists = new ArrayList<>();
            Map<String,Object> guest_list = null;
            while (rs.next()){
                String cfd_new = rs.getString("cfd_new");//出发地cid
                String mdd_new = rs.getString("mdd_new");//目的地cid
                String zzcs = rs.getString("zzcs");//中转城市
                if(!citys.contains(cfd_new)){
                    citys.add(cfd_new);
                }
                if(!citys.contains(mdd_new)){
                    citys.add(mdd_new);
                }
                if(!citys.contains(zzcs)){
                    citys.add(zzcs);
                }
                String zzcs2 = rs.getString("zzcs2");//中转城市2
                String[] _zzcs2 = zzcs2.split(",");
                for(String s : _zzcs2){
                    if(!citys.contains(s)){
                        citys.add(s);
                    }
                }

                String ksrq = rs.getString("ksrq");//开始日期
                String jsrq = rs.getString("jsrq");//结束日期
                if(!dates.contains(ksrq)){
                    dates.add(ksrq);
                }
                if(!dates.contains(jsrq)){
                    dates.add(jsrq);
                }

                //出行人获取
                guest_list = new HashMap<>();
                guest_list.put("name",rs.getString("xingmm"));//同行人姓名
                guest_list.put("phone_num",rs.getString("sjhm"));//联系电话
                guest_lists.add(guest_list);
            }

            //行程内容
            Map<String,Object> trip = new HashMap<>();
            List<Map<String,Object>> multi_trip_citys = new ArrayList<>();

            //添加城市列表
            Map<String,Object> multi_trip_city = null;
            for(String cid : citys){
                multi_trip_city = new HashMap<>();
                multi_trip_city.put("key",cid);
                multi_trip_city.put("value",getCityName(rs,cid));

                multi_trip_citys.add(multi_trip_city);
            }
            trip.put("multi_trip_city",multi_trip_citys);
            //固定出行方式
            int[] multi_trip_scene = new int[]{7,15,135,11};//7-国内机票 15-火车 135-汽车票 11酒店
            trip.put("multi_trip_scene",multi_trip_scene);
            logTool.writeLog("日期区间："+JSONObject.toJSONString(dates));
            trip.put("start_time", Collections.min(dates));//最小日期
            trip.put("end_time",Collections.max(dates));//最大日期

            data.put("apply",data_apply);//申请单内容
            data.put("trip",trip);//行程
            data.put("guest_lists",guest_lists);//同行人
            params.put("data",JSONObject.toJSONString(data));
            String sign = getSign(timestamp,JSONObject.toJSONString(data),sign_key);
            params.put("sign", sign);

            String sfdp = main.get("sfdp");//是否订票 为否时不传分贝通
            String shenqbm = main.get("shenqbm");//申请部门
            RecordSet rs2 = new RecordSet();
            rs2.executeQuery("select isnull(supdepid,0) as supdepid from hrmdepartment where id="+shenqbm);
            rs2.next();
            int supdepid1 = rs2.getInt("supdepid");

            int supdepid2 = 0;
            rs2.execute("with Department as(select * from HrmDepartment where id='"+shenqbm+"'\n" +
                    "union all select d.* from Department,HrmDepartment d where Department.supdepid=d.id)\n" +
                    "select id from Department where supdepid=0");
            if(rs2.next()){
                supdepid2 = rs2.getInt(1);
            }
            logTool.writeLog("申请部门id："+shenqbm+"  上级部门id1："+supdepid1+"  上级部门id2："+supdepid2);
            //申请部门为营销中心下的才传分贝通
            //if(supdepid1==112 || supdepid1==116 || supdepid2==112 || supdepid2==116){
            try{
                logTool.writeLog("请求分贝通差旅接口参数");
                logTool.writeLog(JSONObject.toJSONString(params));
                String result = client.post(app_url+"/openapi/func/apply/trip/multi/create",params);
                logTool.writeLog("分贝通差旅接口结果");
                logTool.writeLog(result);
                JSONObject result_obj = JSONObject.parseObject(result);
                if(result_obj == null || !result_obj.getString("code").equals("0")){
                    requestInfo.getRequestManager().setMessageid(requestid+"");
                    requestInfo.getRequestManager().setMessagecontent(result_obj.getString("msg"));
                    return FAILURE_AND_CONTINUE;
                }
                //将结果反写回中间表 用于接收订单时关联
                String apply_id = result_obj.getJSONObject("data").getString("apply_id");
                String request_id = result_obj.getString("request_id");
                RecordSet rs_result = new RecordSet();
                rs_result.execute("insert into uf_fenbeitong_records(apply_id,request_id,data_id)values('"+apply_id+"','"+request_id+"',"+requestid+")");

                //用车申请
                //构建参数
                Map<String, Object> params2 = new HashMap<>();
                params2.put("access_token", access_token);
                params2.put("sign", sign_key);
                params2.put("timestamp", System.currentTimeMillis());
                Map<String, Object> data2 = new HashMap<>();//请求数据
                Map<String, Object> data_apply2 = new HashMap<>();//申请单内容
                String apply_reason2 = main.get("qt");//备注
                data_apply2.put("apply_reason",apply_reason2);
                String third_id2 = "B_"+requestid;//第三方申请单id
                data_apply2.put("third_id",third_id2);
                int employee_id2 = requestInfo.getRequestManager().getCreater();//人员id
                data_apply2.put("employee_id",employee_id2);
                String apply_reason_desc2 = main.get("qt");//备注
                data_apply2.put("third_remark",apply_reason_desc2);
                data_apply2.put("type","12");
                data_apply2.put("flow_type","12");

                //费用归属对象集合
                List<Map<String,Object>> cost_attribution_list = new ArrayList<>();
                //费用归属 - 部门 start
                Map<String,Object> cost_dep_main2 = new HashMap<>();
                cost_dep_main2.put("cost_attribution_category","1");
                cost_dep_main2.put("cost_attribution_id",main.get("feiygsbm"));//费用归属部门
                cost_dep_main2.put("cost_attribution_name",dbTools.getDepNameById(main.get("feiygsbm")));//费用归属部门
                cost_attribution_list.add(cost_dep_main2);
                //费用归属 - 部门 end
                data_apply2.put("cost_attribution_list",cost_attribution_list);
                //用车的形成只能用一个 是否还需要用车？
                logTool.writeLog("推送分贝通成功 requestid="+requestid);
                return SUCCESS;
            }catch (Exception e){
                e.printStackTrace();
                requestInfo.getRequestManager().setMessageid(requestid+"");
                requestInfo.getRequestManager().setMessagecontent("Call API error "+e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
            //}
            //logTool.writeLog("不需要订票 跳过接口");
            //return SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessageid(requestid+"");
            requestInfo.getRequestManager().setMessagecontent("Application error "+e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
    }

    private String getXmmc(String id){
        if(id.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        rs.execute("select * from uf_xmhdb where id="+id);
        rs.next();
        return  rs.getString("xmmc");
    }
    private String getHetlsh(String id){
        if(id.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        rs.execute("select * from uf_httz where id="+id);
        rs.next();
        return  rs.getString("hetlsh");
    }
    private String getHtmc(String id){
        if(id.isEmpty()) return "";
        RecordSet rs = new RecordSet();
        //rs.execute("select (hetmc+'_'+hetlsh) as htmc from uf_httz where id="+id);
        rs.execute("select (hetlsh+'_'+htdwjf) as htmc from uf_httz where id="+id);
        rs.next();
        return  rs.getString("htmc");
    }
    private String getCityName(RecordSet rs,String cid){
        if(cid.isEmpty()) return "";
        rs.execute("select * from uf_fenbeitong_c where cid='"+cid+"'");
        rs.next();
        return rs.getString("name");
    }

    public static String getSign(String timestamp, String jsonData, String signKey) {
        //使用相对应的方法进行字符串拼接,可以调用不同方法生成签名字符串
        String signStr = MessageFormat.format("timestamp={0}&data={1}&sign_key={2}", timestamp, jsonData, signKey);
        //2.String signStr = "timestamp="+timestamp+"&data="+jsonData+"&sign_key="+signKey
        byte[] bytes;
        try {
            bytes = signStr.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("签名算法异常 "+e.getMessage());
        }
        String sign = DigestUtils.md5Hex(bytes);
        return sign;
    }
}
